/**
 * 
 */
package scriptlerweb

import com.google.appengine.api.users.User 
import com.google.appengine.api.users.UserServiceFactory 
import javax.servlet.Filter;
import javax.servlet.FilterChain 
import javax.servlet.FilterConfig 
import javax.servlet.ServletException;
import javax.servlet.ServletRequest 
import javax.servlet.ServletResponse 
import javax.servlet.http.HttpSession;

import groovyx.gaelyk.logging.GroovyLogger

import org.mortbay.log.Log;

/**
 * @author domi
 *
 */
class OpenIdFilter implements Filter {
	
	String REDIRECT_URI = "openid_login_redirect"
	
	def log = new GroovyLogger("scriptlerweb.OpenIdFilter")
	
	def userSrv 
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
	FilterChain chain) throws IOException, ServletException {
		User logedInUser = userSrv.getCurrentUser()
		
		if (logedInUser != null) {
			chain.doFilter request, response
		} else {
			def identifier = request.getParameter("openid_identifier")
			log.fine "identifier: $identifier"
			if(!identifier){
				request.getSession(true).setAttribute REDIRECT_URI, request.getRequestURI()
				log.finer("redirect to login")
				response.sendRedirect "/login.gtpl"
			}else{
				def redirect = request.getSession(true).getAttribute(REDIRECT_URI);
				
				log.finer("login to $identifier and redirect to $redirect")
				Set<String> attributes = new HashSet();
				String loginUrl = userSrv.createLoginURL(redirect, null, identifier, attributes);
				response.sendRedirect loginUrl
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
		userSrv = UserServiceFactory.getUserService()
	}
}
